package com.gmail.at.service.jpa;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gmail.at.dao.StationDAO;
import com.gmail.at.model.Station;
import com.gmail.at.service.StationService;
import com.google.common.collect.Lists;

@Service("stationService")
@Repository
@Transactional
public class StationServiceImpl implements StationService {

	@Autowired
	private StationDAO stationDAO;

	@Override
	@Transactional(readOnly = true)
	public List<Station> findAll() {
		return Lists.newArrayList(stationDAO.findAll());
	}

	@Override
	@Transactional(readOnly = true)
	public Station findById(Integer id) {
		return stationDAO.findOne(id);
	}

	@Override
	public Station save(Station station) {
		if (stationDAO.findByName(station.getStationName()) == null) {
			return stationDAO.save(station);
		}
		return null;
	}

	@Override
	public Station update(Station station) {
		if (stationDAO.findOne(station.getStationID()).getStationName().equals(station.getStationName())) {
			return stationDAO.save(station);
		} else if (stationDAO.findByName(station.getStationName()) == null) {
			return stationDAO.save(station);
		}
		return null;
	}

	@Override
	public String delete(Integer id) {
		Station station = this.findById(id);
		if (station != null) {
			stationDAO.delete(station);
			return "ok";
		}
		return "no";
	}

	@Transactional(readOnly=true)
	public Page<Station> findAllByPage(Pageable pageable) {
		return stationDAO.findAll(pageable);
	}
}
